<template>
  <Card style="width:100%" class="detail-content-layout mb16">
    <template #title>
      {{ titleObj[type] }}
    </template>
    <template #extra>
      <Icon @click="printPreviewPdf('PAY'+type,info)" style="font-size: 19px; margin-right: 10px;" type="ios-print"/>
      <div class="h-arrow-wrap" @click="toggle = !toggle">
        <i :class="{toggleActive:toggle}" class="iconfont zy-common-jiantou h-arrow-icon"></i>
      </div>
    </template>
    <transition name="slide-up">
      <div v-if="toggle">
        <Form ref="form" :model="form" :rules="rules" label-position="top">
          <Row :gutter="24">
            <Col span="6">
              <FormItem :label="$t('采购单号')" prop="poNo">
                <Input maxlength="45" :disabled="disabled || dtStatus  || !isTypeFirst" clearable type="text" v-model="form.poNo"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('V5的收件日期')" prop="receivingByV5" >
                <DatePicker v-model="form.receivingByV5" :disabled="disabled || dtStatus" type="date"
                            :placeholder="$t('请选择')"></DatePicker>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('规定日期')" prop="requiredDate">
                <DatePicker v-model="form.requiredDate" :disabled="disabled || dtStatus" type="date"
                            :placeholder="$t('请选择')"></DatePicker>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem  :label="$t('付款方式')" prop="payment">
                <Select transfer :disabled="disabled || dtStatus" v-model="form.payment">
                  <Option v-for="(item,index) in paymentList" :value="item.label" :key="index">{{ item.label }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem  :label="$t('收款单位名称')" prop="payeeName">
                <Input maxlength="100" :disabled="disabled || dtStatus || !isTypeFirst" clearable type="text" v-model="form.payeeName"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem  :label="$t('银行账户1')" prop="payeeCode">
                <Input maxlength="100" :disabled="disabled || dtStatus || !isTypeFirst" clearable type="text" v-model="form.payeeCode"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem  :label="$t('开户银行')" prop="payeeBank">
                <Input maxlength="100" :disabled="disabled || dtStatus || !isTypeFirst" clearable type="text" v-model="form.payeeBank"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('付款金额')" prop="dpAmount">
                <InputNumber class="prependMoneyIcon prependIcon" style="width: 100%" max="999999999" :disabled="disabled || dtStatus" clearable type="number" number v-model.number="form.dpAmount"
                       :placeholder="$t('请输入')"
                             :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                             :parser="value => value.replace(/k\￥\s?|(,*)/g, '')">
<!--                             :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"-->
<!--                             :parser="value => value.replace(/\￥\s?|(,*)/g, '')">-->
<!--                >-->
<!--                  <template #prepend>-->
<!--                    <span>k￥</span>-->
<!--                  </template>-->
                </InputNumber>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('支付给')" prop="payedTo">
                <Input maxlength="100" :disabled="disabled || dtStatus" clearable type="text" v-model="form.payedTo"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('部门1')" prop="departmentBranchOrgId">
                <Select filterable transfer v-if="!disabled" :disabled="disabled || dtStatus" v-model="form.departmentBranchOrgId">
                  <Option v-for="item in dpList" :value="item.label" :key="item.value">{{ item.label }}</Option>
                </Select>
                <Input v-else disabled clearable type="text" v-model="form.departmentBranchOrgId"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('申请人')">
                <Input disabled clearable type="text" v-model="form.applyByName" :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('提交人1')" v-if="dtTableStatus && disabled">
                <Input disabled clearable type="text" v-model="form.preparedByName" :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem  :label="$t('描述')">
                <Input maxlength="500" :disabled="disabled || dtStatus" :rows="5" clearable type="textarea" v-model="form.dpDescription"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <downPatmentTable :type="type" v-if="dtTableStatus" ref="downPatmentTable" :list="downPaymentDetailDtos"
                          :disabled="disabled"/>
        <rejectInfo :rejectFlows="rejectFlows"/>
      </div>
    </transition>
  </Card>
</template>

<script>
import mixins from "@/views/devBasic/capex/components/mixins";
import rejectInfo from "@/views/devBasic/capex/components/rejectInfo";
import downPatmentTable from "@/views/devBasic/capex/components/downPatmentTable";
import moment from 'moment'

export default {
  name: "downPayment",
  components: {rejectInfo, downPatmentTable},
  mixins: [mixins],
  props: {
    info: {
      type: Object,
      default: () => {
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    approvalInfo: {
      type: Object,
      default: () => {
      }
    },
    rejectFlows: {
      type: Object,
      default: () => {
      }
    },
    type: {
      type: String,
      default: "1"
    },
    expand: {
      type: Boolean,
      default: false
    },
  },
  data() {
    const validateSelect = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('请选择')));
      } else {
        callback();
      }
    }
    const validateAmout = (rule, value, callback) => {
      if (!this.form.dpAmount) {
        callback(new Error(this.$t('请输入')));
      } else {
        callback();
      }
    };
    return {
      toggle: false,
      form: {
        remark: "",
        poNo: "",
        payeeName: "",
        payeeCode: "",
        payeeBank: "",
        payedTo: "",
        dpAmount: "",
        payment: "",
        receivingByV5: "",
        requiredDate: "",
        departmentBranchOrgId: "",
        dpDescription: "",
      },
      rules: {
        poNo: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'blur'}],
        // receivingByV5: [{trigger: 'change', validator: validateSelect}],
        // requiredDate: [{trigger: 'change', validator: validateSelect}],
        payment: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'change'}],
        payeeName: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'blur'}],
        payeeCode: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'blur'}],
        payeeBank: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'blur'}],
        payedTo: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'blur'}],
        dpAmount:  [{required: true, trigger: 'blur', validator: validateAmout}],
        departmentBranchOrgId: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'change'}],
      },
      dpApprovalInfo: {},
      dtStatus: false,
      dpList: [],
      dtTableStatus: false,
      dpProgressCode: "",
      downPaymentDetailDtos: [],
      titleObj: {
        1: this.$t('支付首期款'),
        2: this.$t('第二次付款'),
        3: this.$t('第三次付款')
      },
      isTypeFirst:true,
    }
  },
  async created() {
    this.form.submitByStr = this.userName
    this.form.departmentBranchOrgId = this.info.cvInfo.cvDepartmentId
    // const dpApprovalInfo = this.getDTApprovalRole(this.info["dpSubmitInfos" + this.type])

    const _type = this.type / 1;
    let Dtype = 'Down Payment'
    if (_type == 1) {
      Dtype = 'Down Payment'
    }
    if (_type == 2) {
      Dtype = '2nd Payment'
    }
    if (_type == 3) {
      Dtype = '3nd Payment'
    }

    this.isTypeFirst = _type ==1 ? true : false
    this.downPaymentDetailDtos = this.info['downPaymentDetailDtos'].filter(item => item.processCode === Dtype)
    let form = this.info['downPaymentDto' + this.type]
    if (form && form.id) {
      this.setParams()
    }else {
      this.form.applyByName = this.userName
      this.form.preparedByName = this.userName
      if (this.info['downPaymentDto1'] && this.info['downPaymentDto1'].id)
        this.setDp1Params()
    }

    // if (dpApprovalInfo && dpApprovalInfo.progressCode) {
    //   this.dpProgressCode = dpApprovalInfo.progressCode
    //   if (this.dpProgressCode === 'ACCOUNTING_S') {
    //     this.dtStatus = true
    //     this.dtTableStatus = true
    //   } else {
    //     this.dtStatus = false
    //     this.dtTableStatus = false
    //   }
    // } else {
    //   this.dtTableStatus = true
    // }

        this.dtStatus = false
        this.dtTableStatus = true

    this.toggle = this.disabled ? false : true

    if (this.expand) {
      this.toggle = true
    }
    if (!this.disabled) {
      this.dpList = await this.getdpList()
    }

  },
  methods: {
    setDp1Params(){
      let {
        poNo,
        payeeName,
        payeeCode,
        payeeBank,
        payedTo,
        payment,
        // departmentBranchOrgId
      } = this.info['downPaymentDto1'];

      this.form = Object.assign(this.form, {
        poNo,
        payeeName,
        payeeCode,
        payeeBank,
        payedTo,
        payment,
        // departmentBranchOrgId
      })

      if (this.type==2){
        this.form.dpDescription = this.info['downPaymentDto1'].dpDescription
      }

      if (this.type==3){
        this.form.dpDescription = this.info['downPaymentDto2'].dpDescription
      }


      this.$forceUpdate()

    },
    setParams() {
      // const {submitRemark} = this.approvalInfo
      let {
        poNo,
        payeeName,
        payeeCode,
        payeeBank,
        payedTo,
        dpAmount,
        payment,
        receivingByV5,
        requiredDate,
        departmentBranchOrgId,
        dpDescription,
        applyByName,
        preparedByName

      } = this.info['downPaymentDto' + this.type];

      this.form = Object.assign(this.form, {
        poNo,
        payeeName,
        payeeCode,
        payeeBank,
        payedTo,
        dpAmount: dpAmount/1,
        payment,
        receivingByV5,
        requiredDate,
        departmentBranchOrgId,
        dpDescription,
        applyByName,
        preparedByName
      })
      this.$forceUpdate()
    },
    setProcessCode(list) {
      list.forEach(item => {
        switch (this.type / 1) {
          case 1:
            item.processCode = 'Down Payment'
            break;
          case 2:
            item.processCode = '2nd Payment'
            break;
          case 3:
            item.processCode = '3nd Payment'
            break;
        }
      })
    },
    async getParams(status) {
      let valid = true
      // if (!this.dtTableStatus) {
        valid = status ?status:await this.$refs.form.validate()
      // }
      if (valid) {
        const form = JSON.parse(JSON.stringify(this.form))
        const params = {
          downPaymentDto: {
            ...form,
            receivingByV5: form.receivingByV5 ? moment(form.receivingByV5).format('YYYY-MM-DD HH:mm:ss') :"",
            requiredDate: form.requiredDate ? moment(form.requiredDate).format('YYYY-MM-DD HH:mm:ss'):"",
          },
          // dpSubmitProgressCode: this.dpProgressCode
          dpSubmitProgressCode: 'PO_A'

        }

        // if (this.dtTableStatus) {
          const list = this.$refs.downPatmentTable.getParams()
          this.setProcessCode(list)
          if (list.find(item => item.edit)) {
            this.$Message.error(this.$t('请先保存'))
            return;
          }
          // if (list.length < 1) {
          //   this.$Message.error(this.$t('最少添加一条数据'))
          //   return;
          // }
          params.downPaymentDetailDtos = list
        // }
        return {
          ...params
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "./style";
</style>

